import React,{useState,useEffect,useRef} from "react"
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
// import PropTypes from "prop-types"
import PropTypes from 'prop-types';
import { faSearch,faTimes } from '@fortawesome/free-solid-svg-icons'

import useKeyPress from "../hooks/useKeyPress.js"
const {ipcRenderer} = window.require("electron")


const FileSearch = ({title,onFileSearch})=>{
  const [inputActive, setInputActive] = useState(false)
  const [value, setValue] = useState('')

  const enterKey = useKeyPress(13)//必须放在里面，不能放在外面
  const escKey = useKeyPress(27)

  const node = useRef(null)

  const closeSearch = ()=>{
    // e.preventDefault();
    setValue("")
    setInputActive(false)
    onFileSearch('');
  }
  useEffect(()=>{
    const searchFileCallback = ()=>{
      setInputActive(true)
    }
     ipcRenderer.on("search-file",searchFileCallback)
     return ()=>{
        ipcRenderer.removeListener("search-file",searchFileCallback)
     }
  })
  useEffect(()=>{
    if(enterKey && inputActive){
      onFileSearch(value.trim())
    }else if(escKey && inputActive){
      closeSearch()
    }

    // const handleInputEvent = (e)=>{
    //    const {keyCode } = e;
    //    if(keyCode ===13 &&  inputActive){
    //       onFileSearch(value)
    //    }else if(keyCode ===27 &&  inputActive){
    //       closeSearch(e)
    //    }
    // }
    // document.addEventListener('keyup',handleInputEvent)
    // return ()=>{
    //   document.removeEventListener('keyup',handleInputEvent)
    // }
  })
  useEffect(()=>{
    if(inputActive){
      node.current.focus()
    }//点击搜索的时候，让input框获取到焦点
  },[inputActive])


  return (
    <div className="alert alert-primary d-flex justify-content-between align-items-center mb-0">
        {!inputActive &&
          <>
            <span className="px-0">{title}</span>
            <button className="icon-btn"
            onClick={()=>{setInputActive(true)}}
            >
              <FontAwesomeIcon icon={faSearch} title="搜索" size="lg"/>
            </button>
          </>
        }
        {inputActive &&
          <>
            <input className="form-control p-0"
            value={value}
            ref={node}
            onChange={(e)=>{setValue(e.target.value)}}
            />
            <button className="icon-btn"
            onClick={(e)=>{closeSearch()}}
            >
              <FontAwesomeIcon icon={faTimes} title="关闭" size="lg"/>
            </button>
          </>
        }
    </div>

  )
}

//属性检查
FileSearch.propTypes = {
  title:PropTypes.string,
  onFileSearch:PropTypes.func.isRequired
}
//默认值
FileSearch.defaultProps={
  title:"我的云文档2"
}


export default FileSearch;
